package xxl.robotlegs.extensions.contextview 
{
	import xxl.robotlegs.extensions.contextview.impl.ContextView;
	import xxl.robotlegs.extensions.matching.impl.InstanceOfMatcher;
	import xxl.robotlegs.framework.api.IContext;
	import xxl.robotlegs.framework.api.IExtension;
	import xxl.robotlegs.framework.api.ILogger;
	
	/**
	 * ...
	 * @author XXL
	 */
	public class StageSyncExtension implements IExtension 
	{
		private var _context:IContext;
		private var _logger:ILogger;
		private var _contextView:ContextView;
		
		public function StageSyncExtension() 
		{
			
		}
		
		public function toString():String
		{
			return "StageSyncExtension（简介：根据contextView是否在场景上的状态，自动初始化或销毁Context）";
		}
		
		private function handleContextView(contextView:ContextView):void
		{
			if (_contextView)
			{
				_logger.warn("ContextView已经安装过了，忽略 {0}", [contextView.view]);
			}
			_contextView = contextView;
			if (contextView.view.stage)
			{
				initializeContext();
			}
			else
			{
				_logger.debug("ContextView还没有在场景上，等待中。。。");
				contextView.displayObjectSignalSet.addedToStage.addOnceWithPriority(onAddedToStage, int.MIN_VALUE).safelyExecute = true;
			}
		}
		
		private function onAddedToStage():void
		{
			initializeContext();
		}
		
		private function initializeContext():void
		{
			_logger.debug("ContextView现在已经在场景上了，初始化context。。。");
			_context.initialize();
			_contextView.displayObjectSignalSet.removedFromStage.addOnce(onRemovedFromStage).safelyExecute = true;
		}
		
		private function onRemovedFromStage():void
		{
			_logger.debug("ContextView从场景上移除了，销毁context。。。");
			_context.destroy();
		}
		
		/* INTERFACE xxl.robotlegs.framework.api.IExtension */
		
		public function extend(context:IContext):void 
		{
			_context = context;
			_logger = context.getLogger(this);
			context.addConfigHandler(new InstanceOfMatcher(ContextView), handleContextView);
		}
		
	}

}